FROM alpine:3.20.1 AS base

RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories \
    && echo '@edge http://mirrors.tuna.tsinghua.edu.cn/alpine/edge/main' >> /etc/apk/repositories \
    && echo '@edgecommunity http://mirrors.tuna.tsinghua.edu.cn/alpine/edge/community' >> /etc/apk/repositories \
    && echo '@testing http://mirrors.tuna.tsinghua.edu.cn/alpine/edge/testing' >> /etc/apk/repositories \
    && apk add --no-cache --update --upgrade su-exec ca-certificates

FROM base AS openrc

RUN apk add --no-cache busybox-openrc \
    && apk add --no-cache --virtual .build-dependencies uuidgen \
    && uuidgen -r > /etc/machine-id \
    # Disable getty's
    && sed -i 's/^\(tty\d\:\:\)/#\1/g' /etc/inittab \
    && sed -i \
        # Change subsystem type to "docker"
        -e 's/#rc_sys=".*"/rc_sys="docker"/g' \
        # Allow all variables through
        -e 's/#rc_env_allow=".*"/rc_env_allow="\*"/g' \
        # Start crashed services
        -e 's/#rc_crashed_stop=.*/rc_crashed_stop=NO/g' \
        -e 's/#rc_crashed_start=.*/rc_crashed_start=YES/g' \
        # Define extra dependencies for services
        -e 's/#rc_provide=".*"/rc_provide="loopback net"/g' \
        /etc/rc.conf \
    # Remove unnecessary services
    && rm -f /etc/init.d/hwdrivers \
            /etc/init.d/hwclock \
            /etc/init.d/hwdrivers \
            /etc/init.d/modules \
            /etc/init.d/modules-load \
            /etc/init.d/modloop \
            /etc/init.d/machine-id \
    # Can't do cgroups
    && sed -i 's/\tcgroup_add_service/\t#cgroup_add_service/g' /lib/rc/sh/openrc-run.sh \
    && sed -i 's/VSERVER/DOCKER/Ig' /lib/rc/sh/init.sh \
    && apk del .build-dependencies

CMD ["/sbin/init"]
